package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.SetmealDishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     *新增套餐接口
     * @author Mosetian
     * @date 2022-9-15 16:36
     * @param	setmealDto
     * @return R
     */
    @Override
    @Transactional
    public R saveSetmealWithDish(SetmealDto setmealDto) {
        //1、保存套餐数据到 setmeal表中 ： SetmealMapper
        int count = setmealMapper.insert(setmealDto);
        //2、保存套餐菜品数据到 setmeal_dish表中： SetmealDishMapper
        //2.1 获取当前套餐的菜品列表
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //2.2 循环遍历，获取每一个套餐菜品数据 setmealDish
        List<SetmealDish> setmealDishList = setmealDishes.stream().map((setmealDish) -> {
            //2.3 获取套餐id，并set到setmealDish中
            setmealDish.setSetmealId(setmealDto.getId());
            //2.4 保存套餐菜品数据 setmealDish
            setmealDishMapper.insert(setmealDish);
            return setmealDish;
        }).collect(Collectors.toList());

        return count>0?R.success("保存套餐成功！！"):R.error("保存套餐失败！！");
    }

    //套餐分页查询
    @Override
    @Transactional
    public R pageWithDish(int page, int pageSize, String name) {
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Setmeal::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        //执行查询条件
        setmealMapper.selectPage(pageInfo, queryWrapper);

        long total = pageInfo.getTotal();
        List<Setmeal> setmeals = pageInfo.getRecords();

        List<SetmealDto> setmealDtos = setmeals.stream().map((setmeal) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(setmeal, setmealDto);
            //分类id
            Long categoryId = setmeal.getCategoryId();
            //根据分类id查询分类对象
            Category category = categoryMapper.selectById(categoryId);
            if (category != null) {
                //分类名称
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        HashMap map = new HashMap();
        map.put("total", total);
        map.put("records", setmealDtos);

        return R.success(map);
    }

    //删除套餐
    @Override
    @Transactional
    public R deleteWithDish(List<Long> ids) {
        //查询套餐状态，确定是否可用删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);

        Integer count = setmealMapper.selectCount(queryWrapper);

        if (count>0){
            //不能删除
            return R.error("套餐正在售卖中，不能删除");
        }

        //如果可以删除，先删除套餐表中的数据---setmeal
        setmealMapper.deleteBatchIds(ids);

        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.in(SetmealDish::getSetmealId,ids);
        //删除关系表中的数据----setmeal_dish
        setmealDishMapper.delete(qw);

        return R.success("套餐删除成功");
    }

    //根据套餐id查询套餐数据,用于回显
    @Override
    @Transactional
    public R<SetmealDto> getByIdWithDish(Long id) {
        Setmeal setmeal = setmealMapper.selectById(id);

        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);

        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId, setmeal.getId());

        List<SetmealDish> setmealDishes = setmealDishMapper.selectList(qw);
        setmealDto.setSetmealDishes(setmealDishes);

        return R.success(setmealDto);
    }

    //修改套餐
    @Override
    @Transactional
    public void updateWithDish(SetmealDto setmealDto) {
        //1、根据id更新 setmeal 套餐表数据 update setmeal set xx=?,.. where id =?
        setmealMapper.updateById(setmealDto);

        //2、操作套餐对应的菜品数据： setmeal_dish
        //2.1 先根据套餐id删除套餐对应的菜品数据： delete from setmeal_dish where setmeal_id =?
        // 获取套餐id   setmealDto.getId()
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId, setmealDto.getId());

        // 使用 setmealDishMapper 根据套餐id进行删除 ：delete from setmeal_dish where setmeal_id =?
        setmealDishMapper.delete(qw);

        //2.2 重新添加新的套餐对应的菜品数据 insert setmeal_dish values (..)
        // setmealDto.getSetmealDishes() 获取套餐的菜品集合 List<SetmealDish>
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
            setmealDishMapper.insert(setmealDish);
        }
    }

    //根据套餐分类id查询该套餐分类下的套餐
    @Override
    @Transactional
    public R listWithCategory(Setmeal setmeal) {

        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        qw.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());

        List<Setmeal> setmeals = setmealMapper.selectList(qw);

        return R.success(setmeals);
    }
}
